﻿function ShowPopup(selector) {
    var box = $(selector);
    box.fadeIn(300);
    var boxMarginTop = box.height() / 2;
    var boxMarginLeft = box.width() / 2;

    box.css({
        'margin-top': -boxMarginTop,
        'margin-left': -boxMarginLeft
    });

    $('body').append('<div id="mask"><div />');
    $("#mask").fadeIn(300);
}

function HidePopup(selector) {
    $('#mask, ' + selector).fadeOut(300, function () {
        $('#mask').remove();
    });
}

function StoryDetailsViewModel(id) {
    var self = this;

    self.story = ko.observable(BlankStory());

    self.characters = ko.observableArray();
    self.characterCategories = ko.observableArray();

    self.selectedCharacter = ko.observable(BlankCharacter());

    self.title = ko.computed(function () {
        return self.story().title();
    });

    self.updateCharacters = function () {
        $.getJSON("/api/character/?storyId=" + story.id(), function (allData) {
            var mappedChars = $.map(allData, function (item) { return new Character(item) });
            self.characters(mappedChars);
        });
    }

    self.updateCharacterCategories = function () {
        $.getJSON("/api/charactercategory", function (allData) {
            var mappedCats = $.map(allData, function (item) { return new CharacterCategory(item) });
            self.characterCategories(mappedCats);
        });
    }

    self.update = function () {
        $.getJSON("/api/story/" + id, function (allData) {
            var story = new Story(allData);
            self.story(story);

            self.updateCharacters();
            self.updateCharacterCategories();
        });
    }

    self.showCharacterDetails = function (data) {
        self.selectedCharacter(data);
        ShowPopup("#viewCharacterBox");
    }

    self.closeCharacterDetails = function () {
        HidePopup("#viewCharacterBox");
    }

    self.update();
}

function ListStoriesViewModel() {
    // Data 
    var self = this;
    self.mode = ko.observable();
    self.editId = -1;

    self.stories = ko.observableArray([]);

    self.editTitle = ko.observable().extend({
        required: true,
        maxLength: 255
    });
    self.editSubtitle = ko.observable().extend({ maxLength: 255 });
    self.editDescription = ko.observable();

    self.loadingStories = ko.observable(false);

    // Operations
    self.update = function () {
        self.loadingStories(true);
        $.getJSON("/api/story", function (allData) {
            var mappedStories = $.map(allData, function (item) { return new Story(item) });
            self.stories(mappedStories);
            self.loadingStories(false);
        });
    }
    self.showStoryBox = function (m) {
        self.mode(m);
        ShowPopup("#newStoryBox");
    }
    self.editStory = function (data) {
        self.editId = data.id();
        self.editTitle(data.title());
        self.editSubtitle(data.subtitle());
        self.editDescription(data.description());
        self.showStoryBox("edit");
    }
    self.startNewStory = function () {
        self.showStoryBox("new");
    };
    self.cancelNewStory = function () {
        self.mode("");
        self.editId = -1;
        self.editTitle("");
        self.editSubtitle("");
        self.editDescription("");

        self.errors.showAllMessages(false);

        self.enableEditBox();

        HidePopup('#newStoryBox');
    }
    self.confirmDelete = function (data) {
        self.idToDelete = data.id();
        ShowPopup("#confirmDeleteBox");
    }
    self.yesDelete = function () {
        $.ajax("/api/story/" + self.idToDelete, {
            type: "delete",
            success: function (result) {
                self.idToDelete = -1
                self.update();
                HidePopup('#confirmDeleteBox');
            }
        });
    }
    self.noDelete = function () {
        self.idToDelete = -1;
        HidePopup('#confirmDeleteBox');
    }
    self.disableEditBox = function () {
        $('#newStory input, #newStory textarea').each(function (index, element) {
            $(element).prop('disabled', true);
        });
    }
    self.enableEditBox = function () {
        $('#newStory input, #newStory textarea').each(function (index, element) {
            $(element).prop('disabled', false);
        });
    }

    self.addStory = function (story) {
        if (self.errors().length == 0) {
            var data = new Object();
            data.Id = self.editId;
            data.UserId = -1;
            data.Title = self.editTitle();
            data.Subtitle = self.editSubtitle();
            data.Description = self.editDescription();

            self.disableEditBox();

            var type;

            if (self.mode() == "new") {
                type = "post";
            }
            else if (self.mode() == "edit") {
                type = "put";
            }
            else {
                return;
            }

            $.ajax("/api/story", {
                data: ko.toJSON(data),
                type: type,
                contentType: "application/json",
                error: function (result) {
                    self.enableEditBox();
                },
                success: function (result) {
                    self.update();
                    self.cancelNewStory();
                }
            });
        }
        else {
            self.errors.showAllMessages();
        }
    }

    self.errors = ko.validation.group(self);

    self.update();
}